package com.vast.admin.utils;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.data.*;
import com.deepoove.poi.data.style.Style;
import com.deepoove.poi.data.style.TableStyle;
import com.vast.admin.entity.RepaymentPlanWord;
import com.vast.system.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.ooxml.POIXMLDocument;
import org.apache.poi.ooxml.extractor.POIXMLTextExtractor;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.xmlbeans.XmlException;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STJc;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class WordUtil {
    /**
     * 读取word文件内容
     *
     * @param path
     * @return buffer
     */

    public static String readWord(String path) {
        String buffer = "";
        try {
            if (path.endsWith(".doc")) {
                HWPFDocument hwpfDocument = new HWPFDocument(new FileInputStream(path));
                WordExtractor wordExtractor = new WordExtractor(hwpfDocument);
                buffer = wordExtractor.getText();
                wordExtractor.close();
            } else if (path.endsWith("docx")) {
                OPCPackage opcPackage = POIXMLDocument.openPackage(path);
                POIXMLTextExtractor extractor = new XWPFWordExtractor(opcPackage);
                buffer = extractor.getText();
                extractor.close();
            } else {
                throw new BusinessException("文件格式错误，无法解析");
            }

        } catch (IOException e) {
            log.error("文件解析失败", e);
            throw new BusinessException("文件解析失败");
        } catch (XmlException e) {
            log.error("文件解析失败", e);
            throw new BusinessException("文件解析失败");
        } catch (OpenXML4JException e) {
            log.error("文件解析失败", e);
            throw new BusinessException("文件解析失败");
        }

        return buffer;
    }

    /**
     * 替换文档中的占位符
     * @param filePath
     * @param outputPath
     * @param param
     */
    public static void replacePlaceholder(String filePath, String outputPath, Map<String, Object> param) {
        FileOutputStream fileOutputStream = null;
        XWPFTemplate xwpfTemplate = null;
//        Map<String, Object> params = new HashMap<>();
//        for(Map.Entry<String, Object> entry : param.entrySet()){
//            String mapKey = entry.getKey();
//            Object mapValue = entry.getValue();
//            if(mapValue instanceof HashMap){
//                HashMap<String,Object> mapValueEntry = (HashMap<String, Object>) mapValue;
//                for(Map.Entry<String, Object> paramEntry : mapValueEntry.entrySet()){
//                    String mapParamKey = paramEntry.getKey();
//                    Object mapParamValue = paramEntry.getValue();
//                    params.put(mapKey+"-"+mapParamKey,mapParamValue);
//                }
//            }else{
//                params.put(mapKey,mapValue);
//            }
//        }
//        System.out.println(params);
        try {
            xwpfTemplate = XWPFTemplate.compile(filePath)
                    .render(param);
            fileOutputStream = new FileOutputStream(outputPath);
            xwpfTemplate.write(fileOutputStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (xwpfTemplate != null) {
                try {
                    xwpfTemplate.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * 生成还款计划数据
     * @return
     */
    public static MiniTableRenderData generateRepaymentPlanData(List<RepaymentPlanWord> repaymentPlanWords) {
        Style fontStyle = new Style();
        fontStyle.setFontSize(12);
//        fontStyle.setFontFamily("仿宋");
        RowRenderData header = new RowRenderData(new ArrayList() {{
            add(new CellRenderData(new TextRenderData("还款日期", fontStyle)));
            add(new CellRenderData(new TextRenderData("期数", fontStyle)));
            add(new CellRenderData(new TextRenderData("应还本金（元）", fontStyle)));
            add(new CellRenderData(new TextRenderData("应还利息（元）", fontStyle)));
            add(new CellRenderData(new TextRenderData("本息合计（元）", fontStyle)));
        }});
        fontStyle.setFontSize(11);
        List<RowRenderData> dataRow = new ArrayList<>();
        for (int i = 0; i < 12 && i < repaymentPlanWords.size(); i ++) {
            RepaymentPlanWord repaymentPlanWord = repaymentPlanWords.get(i);
            RowRenderData data = new RowRenderData(new ArrayList() {{
                add(new CellRenderData(new TextRenderData(repaymentPlanWord.getRepaymentDate(), fontStyle)));
                add(new CellRenderData(new TextRenderData(repaymentPlanWord.getRepaymentIndex(), fontStyle)));
                add(new CellRenderData(new TextRenderData(repaymentPlanWord.getPrincipal(), fontStyle)));
                add(new CellRenderData(new TextRenderData(repaymentPlanWord.getInterest(), fontStyle)));
                add(new CellRenderData(new TextRenderData(repaymentPlanWord.getTotal(), fontStyle)));
            }});
            dataRow.add(data);
        }
        return new MiniTableRenderData(header, dataRow);
    }

    public static void main(String[] args) throws IOException {
        XWPFTemplate xwpfTemplate = XWPFTemplate.compile("D:\\uploadFile\\hetong.docx");
        Map<String, Object> map = new HashMap<>();
        map.put("jihua", WordUtil.generateRepaymentPlanData(new ArrayList() {{
            add(new RepaymentPlanWord("1", "2", "3", "4", "5"));
            add(new RepaymentPlanWord("1", "2", "3", "4", "5"));
            add(new RepaymentPlanWord("1", "2", "3", "4", "5"));
            add(new RepaymentPlanWord("1", "2", "3", "4", "5"));
            add(new RepaymentPlanWord("1", "2", "3", "4", "5"));
            add(new RepaymentPlanWord("1", "2", "3", "4", "5"));
            add(new RepaymentPlanWord("1", "2", "3", "4", "5"));
            add(new RepaymentPlanWord("1", "2", "3", "4", "5"));
            add(new RepaymentPlanWord("1", "2", "3", "4", "5"));
            add(new RepaymentPlanWord("1", "2", "3", "4", "5"));
            add(new RepaymentPlanWord("1", "2", "3", "4", "5"));
            add(new RepaymentPlanWord("1", "2", "3", "4", "5"));
        }}));
        xwpfTemplate.render(map);
        FileOutputStream fileOutputStream = new FileOutputStream("D:\\uploadFile\\test1.docx");
        xwpfTemplate.write(fileOutputStream);

    }

}